﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using PerformanceAssessment.Models;

namespace PerformanceAssessment.Controllers
{
    //[Authorize(Roles = "Administrator")]
    public class AssessmentPeriodsController : Controller
    {
        private PerformanceAssessmentDB db = new PerformanceAssessmentDB();
        //
        // GET: /AssessmentPeriods/

        public ActionResult Index()
        {
            List<AssessmentPeriod> periods = db.AssessmentPeriods.Include("PreviousAssessmentPeriod").ToList();
            return View(periods);
        }

        public ViewResult Details(int id)
        {
            AssessmentPeriod period = db.AssessmentPeriods.Include("PreviousAssessmentPeriod").Include("Teams").Where(p => p.ID == id).FirstOrDefault();
            return View(period);
        }

        public ActionResult Create()
        {
            List<AssessmentPeriod> periods = db.AssessmentPeriods.ToList();
            ViewBag.IdPreviousAssessmentPeriod = new SelectList(periods, "ID", "Description");

            ViewBag.Teams = db.Teams.ToList();
            return View();
        }

        [HttpPost]
        public ActionResult Create(AssessmentPeriod period)
        {
            if (ModelState.IsValid)
            {
                List<int> teamIds = new List<int>();
                foreach (Team team in period.Teams)
                {
                    if (team.Selected)
                    {
                        teamIds.Add(team.ID);
                    }
                }
                period.Teams = (from t in db.Teams
                               where teamIds.Contains(t.ID)
                               select t).ToList();
                db.AssessmentPeriods.Add(period);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            List<AssessmentPeriod> periods = db.AssessmentPeriods.ToList();
            ViewBag.IdPreviousAssessmentPeriod = new SelectList(periods, "ID", "Description", period.IdPreviousAssessmentPeriod);

            ViewBag.Teams = db.Teams.ToList();

            return View(period);
        }

        public ActionResult Edit(int id)
        {
            AssessmentPeriod period = db.AssessmentPeriods.Include("Teams").Where(p => p.ID == id).FirstOrDefault();
            List<AssessmentPeriod> periods = db.AssessmentPeriods.ToList();
            ViewBag.IdPreviousAssessmentPeriod = new SelectList(periods, "ID", "Description", period.IdPreviousAssessmentPeriod);

            List<Team> teams = db.Teams.ToList();
            foreach (Team t in teams)
            {
                if (period.Teams.Where(tm => tm.ID == t.ID).FirstOrDefault() != null)
                {
                    t.Selected = true;
                }
            }
            period.Teams = teams;

            return View(period);
        }

        [HttpPost]
        public ActionResult Edit(AssessmentPeriod period)
        {
            if (ModelState.IsValid)
            {
                AssessmentPeriod savePeriod = db.AssessmentPeriods.Include("Teams").Where(p => p.ID == period.ID).FirstOrDefault();
                List<int> teamIds = new List<int>();
                foreach (Team team in period.Teams)
                {
                    if (team.Selected)
                    {
                        teamIds.Add(team.ID);
                    }
                }
                List<Team> teamsSel = (from t in db.Teams
                                       where teamIds.Contains(t.ID)
                                       select t).ToList();

                savePeriod.Description = period.Description;
                savePeriod.FromDate = period.FromDate;
                savePeriod.ToDate = period.ToDate;
                savePeriod.IdPreviousAssessmentPeriod = period.IdPreviousAssessmentPeriod;
                savePeriod.Teams.Clear();

                foreach (Team t in teamsSel)
                {
                    savePeriod.Teams.Add(t);
                }

                db.Entry(savePeriod).State = System.Data.EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            List<AssessmentPeriod> periods = db.AssessmentPeriods.ToList();
            ViewBag.IdPreviousAssessmentPeriod = new SelectList(periods, "ID", "Description", period.IdPreviousAssessmentPeriod);
            List<Team> teams = db.Teams.ToList();
            foreach (Team t in teams)
            {
                if (period.Teams.Where(tm => tm.ID == t.ID).FirstOrDefault() != null)
                {
                    t.Selected = true;
                }
            }
            period.Teams = teams;
            return View(period);
        }

        public ActionResult Delete(int id)
        {
            AssessmentPeriod period = db.AssessmentPeriods.Include("PreviousAssessmentPeriod").Include("Teams").Where(p => p.ID == id).FirstOrDefault();
            return View(period);
        }

        //
        // POST: /Skill/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            AssessmentPeriod period = db.AssessmentPeriods.Include("Teams").Where(p => p.ID == id).FirstOrDefault();
            var usedPeriods = (from a in db.Assessments
                              where a.IdAssessmentPeriod == id
                              select a.IdAssessmentPeriod).Union(
                             from p in db.AssessmentPeriods
                             where p.IdPreviousAssessmentPeriod == id
                             select p.ID);

            if (usedPeriods.Count() > 0)
                throw new DependencyFoundException("The selected Assessment Period cannot be deleted because it has dependencies on other objects such as opened Assessments or is set as the Previous Assessment Period of another opened period.");
            db.AssessmentPeriods.Remove(period);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult SendNotification(int periodId)
        {
            try
            {
                AssessmentPeriod period = db.AssessmentPeriods.Include("Teams").Include("Teams.Employees").Where(p => p.ID == periodId).FirstOrDefault();
                EmailUtil email = period.GetAutoevaluationOpenEmail();
                email.Send();
            }
            catch (Exception)
            {
                return Json(new { valid = false, error = "An error occurred and the emails could not be sent." }); ;
            }
            return Json(new { valid = true, error = "The notification emails were sent to the Employees successfully."});;
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }
    }
}
